package com.xjj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjj.entity.Manager;
import com.xjj.entity.Vote;
import com.xjj.entity.VoteOption;
import com.xjj.mapper.VoteMapper;
import com.xjj.service.VoteService;
import com.xjj.vo.VoteVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.xjj.utils.RedisCache.CACHE_VOTEDETAILS_KEY;
import static com.xjj.utils.RedisCache.CACHE_VOTELIST_KEY;

/**
 * @author GH
 * @date 2022/10/20 10:37
 */
@Service
@Slf4j
@Transactional
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements VoteService {
    @Resource
    private VoteMapper voteMapper;

    @Resource
    private RedisTemplate redisTemplate;

//    @Resource
//    private ManageFeignClient manageFeignClient;

    @Override
    public void cancelVote(Integer voteId) {
        //修改数据库中的status为1
        voteMapper.cancelVote(voteId);
        //获取行数和对应的页数
        Integer rowNum = voteMapper.getRowNum(voteId);
        Integer currentPage = (rowNum/5)+1;
        //获取班级id
        Integer klassId = voteMapper.getDetailsById(voteId).getKlassId();
        //删除缓存
        redisTemplate.delete(CACHE_VOTELIST_KEY+klassId+":"+currentPage);
        redisTemplate.delete(CACHE_VOTEDETAILS_KEY + voteId);
    }

    @Override
    public boolean voteTimeOut(Integer voteId) {
        //修改数据库中的status为2
        boolean hasUpdate = voteMapper.voteTimeOut(voteId);
        //获取行数和对应的页数
        Integer rowNum = voteMapper.getRowNum(voteId);
        Integer currentPage = (rowNum/5)+1;
        //获取班级id
        Integer klassId = voteMapper.getDetailsById(voteId).getKlassId();
        //将detalis中缓存的数量同步到数据库
        Integer votedNum = (Integer) redisTemplate.opsForHash().get(CACHE_VOTEDETAILS_KEY + voteId, "votedNum");
        voteMapper.setVotedNum(voteId,votedNum);
        List<VoteOption> voteOption = (List<VoteOption>) redisTemplate.opsForHash().get(CACHE_VOTEDETAILS_KEY + voteId, "voteOption");
        for (VoteOption option : voteOption) {
            voteMapper.setOptionNum(option.getId(),option.getNum());
        }
        //删除缓存
        redisTemplate.delete(CACHE_VOTELIST_KEY+klassId+":"+currentPage);
        redisTemplate.delete(CACHE_VOTEDETAILS_KEY + voteId);
        return hasUpdate;
    }


    @Override
    public void deleteById(Integer voteId) {
        //获取班级id
        Integer klassId = voteMapper.getDetailsById(voteId).getKlassId();
        //删除数据库中的数据
        voteMapper.deleteById(voteId);
        voteMapper.deleteOptionById(voteId);
        //获取行数和对应的页数
        Integer rowNum = voteMapper.getRowNum(voteId);
        Integer currentPage = (rowNum/5)+1;
        //删除缓存
        redisTemplate.delete(CACHE_VOTELIST_KEY+klassId+":"+currentPage);
        redisTemplate.delete(CACHE_VOTEDETAILS_KEY + voteId);
    }

    /**
     * @param klassId:
     * @param current:
     * @return Page<Vote>
     * @author GH
     * @description 分页条数为5,按班级id查询
     * @date 2022/10/21 9:58
     */
    @Override
    public Page<Vote> getVotes(Integer klassId, Integer current) {
        Page<Vote> page = new Page<>(current,5);
        QueryWrapper<Vote> queryWrapper = new QueryWrapper<>();
        Vote vote = new Vote();
        vote.setKlassId(klassId);
        queryWrapper.select("*");
        queryWrapper.eq("klass_id",vote.getKlassId());
        page = voteMapper.selectPage(page, queryWrapper);
        List<Vote> votes = page.getRecords();
        for (Vote vote1 : votes) {
            //ResponseEntity<Manager> response = manageFeignClient.getManagerById(vote1.getSenderId());
            //vote1.setManager(response.getData());
            Manager manager = voteMapper.getManagerById(vote1.getSenderId());
            vote1.setManager(manager);
        }
        return page;
    }

    @Override
    public void addVote(VoteVo voteVo) {
        Vote vote = voteVo.getVote();
        //设置开始时间
        Date date=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = df.format(date);
        voteVo.getVote().setStartTime(nowTime);
        //设置初始状态为0(进行中)
        voteVo.getVote().setStatus("0");
        //更新数据库
        voteMapper.insert(vote);
        Integer id = vote.getId();
        String[] texts = voteVo.getText();
        for (String s : texts) {
            voteMapper.addVoteOption(id,s);
        }
        //获取当前最大分页数
        Integer klassId = vote.getKlassId();
        QueryWrapper<Vote> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("klass_id",klassId);
        Long count = voteMapper.selectCount(queryWrapper);
        int pageCount = (int) (count/5)+1;
        //删除缓存
        for (int i = 1; i <= pageCount; i++) {
            redisTemplate.delete(CACHE_VOTELIST_KEY+klassId+":"+i);
        }

    }

    @Override
    public Vote getDetailsById(Integer id) {
        Vote vote = voteMapper.getDetailsById(id);
        return vote;
    }

}
